package com.zhenyi.youqu.admin.index;

import java.util.List;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.youqu.common.model.YqShopUser;
import com.youqu.common.model.YqUser;

public class UserController extends YQAdminController {

	@Override
	public void list() {
		YqShopUser shopUser = getShopUser();
		Kv kv = getSimpleKv("keyword", "isVIP", "isDisable");
		if (!shopUser.getRole().equals(YqShopUser.ROLE_SUPER_ADMIN)) {
			kv.set("appId", shopUser.getAppId());
		}
		SqlPara sqlPara = db.getSqlPara("YQUsers", kv);
		Page<YqUser> pages = YqUser.dao.paginate(getPage(), getPageSize(), sqlPara);
		setRainbow(pages);
		List<YqUser> list = pages.getList();
		for (YqUser user : list) {
			if (StrKit.isBlank(user.getCode())) {
				user.setCode(HASHID.encode(user.getId()));
				user.update();
			}
		}
		setData("items", list);
		render("/yq/admin/user/list.html");
	}

	@Override
	public void info() {
	}

	@Override
	public void submit() {
	}

	@Override
	public void delete() {
	}

	private Page<Record> getProductByType(int type, Long userId) {
		Kv kv = Kv.by("userId", userId);
		if (type == 1) {
			kv.set("isProduct", 1);
		} else if (type == 2) {
			kv.set("isGroup", 1);
		} else if (type == 3) {
			kv.set("isCard", 1);
		} else {
			return null;
		}
		SqlPara sqlPara = db.getSqlPara("YQOrderGroupCardProduct", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		return pages;
	}

	/**
	 * 用户购买的产品
	 */
	public void product() {
		Integer type = getParaToInt("type");
		if (type == null) {
			renderFailure("type is null");
			return;
		}
		if (type > 3) {
			renderFailure("type error");
			return;
		}
		Long userId = getParaToLong("userId");
		Page<Record> pages = getProductByType(type, userId);
		setRainbow(pages);
		List<Record> list = pages.getList();
		System.out.println(JsonKit.toJson(list));
		setData("items", list);
		render("/yq/admin/user/product.html");
	}

}
